<template>
  <el-dialog
    :close-on-click-modal="false"
    :title="title"
    :visible.sync="dialogFormVisible"
    width="800px"
    @close="close"
  >
    <div class="video-box">
      <el-form ref="form" inline label-width="80px" :model="form">
        <el-form-item label="时间范围" prop="dateArr">
          <el-date-picker
            v-model="form.dateArr"
            clearable
            end-placeholder="结束时间"
            range-separator="至"
            start-placeholder="开始时间"
            type="datetimerange"
            value-format="yyyyMMddHHmmss"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="selectData">查询</el-button>
        </el-form-item>
      </el-form>
      <div id="playerBox" ref="player" class="player-box">
        <canvas
          id="backCanvas"
          ref="canvas"
          :style="{
            width: width + 'px',
            height: height + 'px',
            border: '1px solid #ddd',
          }"
        />
      </div>
    </div>
  </el-dialog>
</template>

<script>
  import { historyVideo } from '@/api/sys'
  import { loadDynamicScript } from '@/utils'
  import dayjs from 'dayjs'
  import { Loading } from 'element-ui'
  let playerInstance = null
  export default {
    name: 'HistoryVideo',
    data() {
      return {
        form: {
          dateArr: '',
        },
        title: '视频回放',
        dialogFormVisible: false,
        intervalId: null,
        deviceId: null,
        deviceNo: null,
        width: 760,
        height: 400,
        startTime: null,
        endTime: null,
        playUrl: '',
        playIsLoaded: false,
        hlsInstance: null,
        isDataLoading: false,
        videoKey: null,
      }
    },
    mounted() {
      loadDynamicScript('static/jsmpeg.min.js', 'jsMpeg', (err) => {
        if (err) {
          console.log('jsmpeg 加载失败！')
        } else {
          console.log('jsmpeg 加载成功！')
        }
      })
    },
    methods: {
      selectData() {
        if (this.form.dateArr && Array.isArray(this.form.dateArr)) {
          // console.log(this.form.dateArr)
          this.startTime = this.form.dateArr[0]
          this.endTime = this.form.dateArr[1]
          if (!this.startTime) {
            this.$baseMessage(
              '开始时间不能为空！',
              'error',
              'vab-hey-message-error'
            )
            return
          }
          if (!this.endTime) {
            this.$baseMessage(
              '结束时间不能为空！',
              'error',
              'vab-hey-message-error'
            )
            return
          }
          this.getFirstLoop()
        } else {
          this.$baseMessage(
            '查询时间范围不能为空！',
            'error',
            'vab-hey-message-error'
          )
        }
      },
      showEdit(row) {
        this.dialogFormVisible = true
        this.deviceId = row.id
        this.deviceNo = row.deviceNo
        this.startTime = dayjs().subtract(14, 'hour').format('YYYYMMDDHHmmss')
        this.endTime = dayjs().subtract(12, 'hour').format('YYYYMMDDHHmmss')
        this.canvasReset()
        this.getFirstLoop()
      },
      close() {
        // console.log(playerInstance)
        this.dialogFormVisible = false
        this.startTime = null
        this.endTime = null
        this.$refs['form'].resetFields()
        this.form = this.$options.data().form
        this.closeAndStopSocket()
        clearInterval(this.intervalId)
      },
      closeAndStopSocket() {
        try {
          if (playerInstance) {
            // if (playerInstance.source && playerInstance.source.socket) {
            //   playerInstance.source.socket.close()
            // }
            // playerInstance.stop()
            playerInstance.destroy()
          }
        } catch (e) {
          console.log(e)
        }
      },
      canvasReset() {
        // setTimeout(() => {
        // const canvas = this.$refs['canvas']
        // console.log(canvas)
        // if (canvas) {
        //   const ctx = canvas.getContext('2d')
        //   ctx.fillStyle = '#000000'
        //   ctx.fillRect(0, 0, this.width, this.height)
        // }
        // }, 100)
      },
      getFirstLoop() {
        this.videoKey = Date.now()
        let loadingInstance = null
        this.$nextTick(() => {
          loadingInstance = Loading.service({ target: this.$refs.player })
        })
        historyVideo(this.deviceId, this.startTime, this.endTime, this.videoKey)
          .then((res) => {
            // console.log(res)
            if (res && res.status === 0 && res.data) {
              // console.log(playerInstance)
              if (playerInstance) {
                playerInstance.stop()
              }
              const playUrl = res.data.videoUrl
              const baseVideoUrl =
                process.env.NODE_ENV === 'development'
                  ? '47.93.117.40:18181'
                  : location.host
              const url = 'ws://' + baseVideoUrl + '/video-ws/' + playUrl
              let canvasDom = document.getElementById('backCanvas')
              const videoBox = document.getElementById('playerBox')
              // console.log(canvasDom)
              if (!canvasDom) {
                canvasDom = document.createElement('canvas')
                canvasDom.id = 'backCanvas'
                canvasDom.style.width = `${this.width}px`
                canvasDom.style.height = `${this.height}px`
                canvasDom.style.border = '1px solid #ddd'
                canvasDom.ref = 'canvas'
                videoBox.appendChild(canvasDom)
              }
              // console.log(canvasDom)
              /* eslint-disable */
              playerInstance = new JSMpeg.Player(url, {
                canvas: canvasDom,
                autoplay: true,
              })
              this.getLoop()
            } else {
              this.$baseMessage(
                res ? res.msg : '获取播放地址失败！',
                'error',
                'vab-hey-message-error'
              )
            }
          })
          .catch((err) => {
            console.log(err)
            this.$baseMessage(
              '网络错误，请重试！',
              'error',
              'vab-hey-message-error'
            )
          })
          .then(() => {
            if(loadingInstance) {
              loadingInstance.close()
            }
          })
      },
      getLoop() {
        clearInterval(this.intervalId)
        this.intervalId = setInterval(() => {
          if (this.startTime && this.endTime) {
            historyVideo(
              this.deviceId,
              this.startTime,
              this.endTime,
              this.videoKey
            )
              .then(() => {})
              .catch(() => {})
          }
        }, 180000)
      },
    },
  }
</script>
<style lang="scss" scoped>
  .video-box {
    padding: 0;
  }
</style>
